<template>
  <div class="player-list">
    <div class="content-card">
      <div class="stats-bar" v-loading="statsLoading">
        <div class="stat-item rank-stat">
          <div class="stat-number">{{ statistics?.totalPlayers || 0 }}</div>
          <div class="stat-label">总选手数</div>
        </div>
        <div 
          v-for="rank in displayRanks" 
          :key="rank.rank"
          class="stat-item rank-stat"
          :style="{ borderTop: `3px solid ${rank.color}` }"
        >
          <div class="stat-number" :style="{ color: rank.color }">{{ rank.count }}</div>
          <div class="stat-label">{{ rank.label }}</div>
        </div>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <div class="search-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索数字ID或昵称"
            style="width: 250px"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="selectedRank"
            placeholder="筛选段位"
            style="width: 150px"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="rank in allRanks"
              :key="rank.value"
              :label="rank.label"
              :value="rank.value"
            />
          </el-select>

          <el-select
            v-model="selectedPosition"
            placeholder="筛选位置"
            style="width: 150px"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="position in allPositions"
              :key="position.value"
              :label="position.label"
              :value="position.value"
            />
          </el-select>
        </div>
        
        <div class="search-right">
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button type="primary" @click="showCreateDialog" class="add-btn" v-if="canAdd">
            <el-icon><Plus /></el-icon>
            添加选手
          </el-button>
        </div>
      </div>

      <el-table 
        :data="players" 
        style="width: 100%" 
        v-loading="loading"
        class="player-table"
        :header-cell-style="{ background: '#fafafa', color: '#606266' }"
        stripe
      >
        <el-table-column prop="id" label="数字ID" width="160" align="center" class-name="el-table__column--id">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{ row.id }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="nickname" label="昵称">
          <template #default="{ row }">
            <span class="nickname">{{ row.nickname }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="擅长位置" width="200" class-name="el-table__column--positions">
          <template #default="{ row }">
            <div class="positions-container">
              <el-tag
                v-for="position in row.positions"
                :key="position"
                size="small"
                :type="getPositionTagType(position)"
                class="position-tag"
              >
                {{ getPositionLabel(position) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="段位" width="120" align="center" class-name="el-table__column--rank">
          <template #default="{ row }">
            <el-tag 
              :type="getRankTagType(row.rank)" 
              size="default"
              class="rank-tag"
            >
              {{ getRankLabel(row.rank) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="最高天梯分" width="100" align="center" class-name="el-table__column--mmr">
          <template #default="{ row }">
            <span class="mmr-text">{{ row.highestMmr }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="能力值" width="180" align="center" class-name="el-table__column--ability">
          <template #default="{ row }">
            <el-rate 
              v-model="row.ability" 
              :max="6" 
              disabled 
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="词条属性" width="250" class-name="el-table__column--tags">
          <template #default="{ row }">
            <div class="tags-container">
              <template v-if="row.tags && row.tags.length > 0">
                <el-tag
                  v-for="tag in row.tags"
                  :key="tag"
                  size="small"
                  type="info"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </template>
              <template v-else>
                <el-tag
                  size="small"
                  type="warning"
                  class="tag-item"
                  style="color: #909399; border-color: #dcdfe6; background-color: #f5f7fa;"
                >
                  快来添加印象吧
                </el-tag>
              </template>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="showActionsColumn" label="操作" width="150" align="center" class-name="el-table__column--actions">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                size="small" 
                type="primary" 
                @click="editPlayer(row)"
                class="action-btn"
                v-if="canEdit"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="deletePlayer(row.id)"
                class="action-btn"
                v-if="canDelete"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="players.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无选手数据">
          <el-button type="primary" @click="showCreateDialog" v-if="canAdd">添加第一个选手</el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 10, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :prev-text="'上一页'"
          :next-text="'下一页'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <PlayerForm v-model:visible="dialogVisible" :player="currentPlayer" @success="handleFormSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import type { Player, PlayerStatistics, PlayerSearchParams } from '@dx-fun-group/shared-types'
import { PlayerRank, PlayerPosition } from '@dx-fun-group/shared-types'
import { deletePlayer as deletePlayerService, getPlayerStatistics, searchPlayers } from '../../services/playerService'
import { getPositionLabel, getRankLabel } from '../../utils/playerUtils'
import PlayerForm from './PlayerForm.vue'
import { useUserStore } from '../../stores/user'

const players = ref<Player[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentPlayer = ref<Player | null>(null)
const statistics = ref<PlayerStatistics | null>(null)
const statsLoading = ref(false)

// 分页和搜索状态
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const searchKeyword = ref('')
const selectedRank = ref<PlayerRank | ''>('')
const selectedPosition = ref<PlayerPosition | ''>('')

// 权限控制
const userStore = useUserStore()
const canAdd = computed(() => userStore.hasPermission('player:add'))
const canEdit = computed(() => userStore.hasPermission('player:edit'))
const canDelete = computed(() => userStore.hasPermission('player:delete'))

// 选项数据
const allRanks = [
  { value: PlayerRank.HERALD, label: '先锋' },
  { value: PlayerRank.GUARDIAN, label: '卫士' },
  { value: PlayerRank.CRUSADER, label: '中军' },
  { value: PlayerRank.ARCHON, label: '统帅' },
  { value: PlayerRank.LEGEND, label: '传奇' },
  { value: PlayerRank.ANCIENT, label: '万古流芳' },
  { value: PlayerRank.DIVINE, label: '超凡入圣' },
  { value: PlayerRank.IMMORTAL, label: '冠绝一世' }
]

const allPositions = [
  { value: PlayerPosition.CARRY, label: '优势路' },
  { value: PlayerPosition.MID, label: '中路' },
  { value: PlayerPosition.OFFLANE, label: '劣势路' },
  { value: PlayerPosition.SUPPORT, label: '辅助' },
  { value: PlayerPosition.HARD_SUPPORT, label: '纯辅助' }
]

const getRankTagType = (rank: PlayerRank): 'info' | 'warning' | 'success' | 'danger' => {
  const rankTypes: Record<PlayerRank, 'info' | 'warning' | 'success' | 'danger'> = {
    [PlayerRank.HERALD]: 'info',
    [PlayerRank.GUARDIAN]: 'info',
    [PlayerRank.CRUSADER]: 'warning',
    [PlayerRank.ARCHON]: 'warning',
    [PlayerRank.LEGEND]: 'success',
    [PlayerRank.ANCIENT]: 'success',
    [PlayerRank.DIVINE]: 'danger',
    [PlayerRank.IMMORTAL]: 'danger'
  }
  return rankTypes[rank]
}

const getPositionTagType = (position: PlayerPosition): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const positionTypes: Record<PlayerPosition, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    [PlayerPosition.CARRY]: 'primary',
    [PlayerPosition.MID]: 'success',
    [PlayerPosition.OFFLANE]: 'warning',
    [PlayerPosition.SUPPORT]: 'info',
    [PlayerPosition.HARD_SUPPORT]: 'danger'
  }
  return positionTypes[position]
}



// 从接口获取统计数据
const displayRanks = computed(() => {
  return statistics.value?.rankStatistics || []
})

const loadPlayers = async () => {
  loading.value = true
  try {
    const params: PlayerSearchParams = {
      keyword: searchKeyword.value,
      rank: selectedRank.value || undefined,
      position: selectedPosition.value || undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response = await searchPlayers(params)
    players.value = response.data.items
    total.value = response.data.total
    console.log('加载的选手数据:', response.data)
  } catch (error) {
    ElMessage.error('加载选手数据失败')
    console.error('加载选手数据失败:', error)
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  statsLoading.value = true
  try {
    statistics.value = await getPlayerStatistics()
    console.log('加载的统计数据:', statistics.value)
  } catch (error) {
    ElMessage.error('加载统计数据失败')
    console.error('加载统计数据失败:', error)
  } finally {
    statsLoading.value = false
  }
}

const showCreateDialog = () => {
  currentPlayer.value = null
  dialogVisible.value = true
}

const editPlayer = (player: Player) => {
  currentPlayer.value = player
  dialogVisible.value = true
}

const deletePlayer = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个选手吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const success = await deletePlayerService(id)
    if (success) {
      ElMessage.success('删除成功')
      await Promise.all([loadPlayers(), loadStatistics()])
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 搜索处理
const handleSearch = async () => {
  currentPage.value = 1 // 重置到第一页
  await loadPlayers()
}

// 分页处理
const handleSizeChange = async (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  await loadPlayers()
}

const handleCurrentChange = async (val: number) => {
  currentPage.value = val
  await loadPlayers()
}

const handleFormSuccess = async () => {
  await Promise.all([loadPlayers(), loadStatistics()])
  dialogVisible.value = false
}

const showActionsColumn = canEdit;

onMounted(() => {
  Promise.all([loadPlayers(), loadStatistics()])
})
</script>

<style scoped>
.player-list {
  padding: 0;
  height: 88vh;
  width: 100%;
  overflow: hidden; /* 移除所有滚动条 */
}

.add-btn {
  font-weight: 500;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 88vh; /* 减去200px的高度 */
}

@media (max-width: 768px) {
  .content-card {
    height: calc(100vh - 24px);
  }
}

.search-bar {
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
  background: #fafafa;
  flex-shrink: 0; /* 防止搜索栏被压缩 */
  display: flex;
  justify-content: space-between;
  align-items: center;
}

@media (max-width: 768px) {
  .search-bar {
    padding: 16px;
  }
}

.search-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.search-right {
  flex-shrink: 0;
  display: flex;
  gap: 12px;
}

.search-btn,
.add-btn {
  width: 100px;
  height: 32px;
}

@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-left {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .search-left .el-input,
  .search-left .el-select {
    width: 100% !important;
  }
  
  .search-right {
    width: 100%;
    justify-content: center;
  }
  
  .search-btn,
  .add-btn {
    width: 120px;
  }
}

.player-table {
  --el-table-border-color: transparent;
}

.player-table .el-table__row {
  transition: background-color 0.25s ease;
}

.player-table .el-table__row:hover {
  background-color: #f5f7fa !important;
}

.pagination-wrapper {
  padding: 20px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #e9ecef;
  background: #fafafa;
  flex-shrink: 0; /* 防止分页栏被压缩 */
}

@media (max-width: 768px) {
  .pagination-wrapper {
    padding: 16px;
    justify-content: center;
  }
  
  .pagination-wrapper .el-pagination {
    font-size: 14px;
  }
}

.stats-bar {
  display: flex;
  flex-wrap: wrap;
  padding: 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  gap: 8px;
  flex-shrink: 0; /* 防止统计栏被压缩 */
}

@media (max-width: 768px) {
  .stats-bar {
    padding: 16px;
    gap: 12px;
  }
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  min-width: 120px;
  flex: 1;
}

@media (max-width: 768px) {
  .stat-item {
    flex: 1 1 calc(50% - 6px);
    min-width: 0;
    padding: 12px;
  }
}

.rank-stat {
  flex: 1;
  position: relative;
  transition: all 0.3s ease;
}

.rank-stat:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}



.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.player-table {
  margin: 0;
  width: 100% !important;
  flex: 1;
  overflow: hidden;
}

/* 表格容器样式 */
.player-table .el-table__body-wrapper {
  overflow-y: auto;
  max-height: calc(100vh - 400px); /* 减去头部、搜索栏、统计栏、分页栏的高度 */
}

.player-table .el-table__body-wrapper {
  width: 100%;
  overflow-y: auto;
  max-height: 400px; /* 设置固定高度 */
}

@media (max-width: 768px) {
  .player-table .el-table__body-wrapper {
    max-height: 300px;
  }
}

.player-table .el-table__header-wrapper {
  width: 100%;
}

/* 移动端表格优化 */
@media (max-width: 768px) {
  .player-table {
    font-size: 14px;
  }
  
  .player-table .el-table__header {
    font-size: 12px;
  }
  
  .player-table .el-table__cell {
    padding: 8px 4px;
  }
  
  /* 隐藏某些列在移动端 */
  .player-table .el-table__column--created-time {
    display: none;
  }
  
  /* 调整列宽 */
  .player-table .el-table__column--id {
    width: 80px !important;
  }
  
  .player-table .el-table__column--positions {
    width: 120px !important;
  }
  
  .player-table .el-table__column--rank {
    width: 80px !important;
  }
  
  .player-table .el-table__column--mmr {
    width: 70px !important;
  }
  
  .player-table .el-table__column--ability {
    width: 80px !important;
  }
  
  .player-table .el-table__column--tags {
    width: 120px !important;
  }
  
  .player-table .el-table__column--actions {
    width: 100px !important;
  }
}

.nickname {
  font-weight: 500;
  color: #303133;
}

.positions-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.position-tag {
  margin: 2px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-item {
  margin: 1px;
}

@media (max-width: 768px) {
  .positions-container {
    gap: 2px;
  }
  
  .position-tag {
    margin: 1px;
    font-size: 12px;
  }
  
  .tags-container {
    gap: 2px;
  }
  
  .tag-item {
    font-size: 12px;
  }
}

.rank-tag {
  font-weight: 500;
}

.time-text {
  color: #909399;
  font-size: 14px;
}

.mmr-text {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-btn {
    font-size: 12px;
    padding: 4px 8px;
  }
}

.empty-state {
  padding: 60px 24px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .stats-bar {
    flex-direction: column;
    gap: 16px;
  }
  
  .stat-item {
    margin: 0;
  }
}
</style>
